package com.example.handler.overflow;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

import androidx.appcompat.app.AppCompatActivity;

import com.example.handler.MainActivity;
import com.example.handler.R;

import java.lang.ref.WeakReference;
import java.util.Timer;
import java.util.TimerTask;


public class Empty_Handler extends AppCompatActivity {
    // 主线程创建时便自动创建Looper和对应的MessageQueue
    // 之后执行Loop()进入消息循环
    private CalThread calThread;
    private static class MyStaticHandler extends Handler {
        // 定义弱引用实例
        private WeakReference<Empty_Handler> mainActivityWeakReference;

        public MyStaticHandler(Empty_Handler activity) {
            // 使用WeakReference弱引用持有Activity实例
            this.mainActivityWeakReference = new WeakReference<>(activity);
        }

        // 通过重写handlerMessage() 从而确定更新UI的操作
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    Log.d("MyHandler", "1的消息");
                    break;
                case 2:
                    Log.d("MyHandler", " 收到线程2的消息");
                    break;
            }
            for (int i = 0; i < 5; i++) {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println(i);
            }
        }
    }


    class CalThread extends Thread
    {
        public MyStaticHandler mHandler;

        public void run() {
            Looper.prepare();// Looper.prepare()来给线程创建消息循环
            mHandler = new MyStaticHandler(Empty_Handler.this);
            Looper.loop();//Looper.loop()来使消息循环起作用。
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_handler);
        calThread = new CalThread();
        calThread.start();

        while ( calThread.mHandler==null);
        calThread.mHandler.sendEmptyMessage(1);
        calThread.mHandler.sendEmptyMessage(1);
        calThread.mHandler.sendEmptyMessage(1);
        calThread.mHandler.sendEmptyMessage(1);
        calThread.mHandler.sendEmptyMessage(1);
        calThread.mHandler.sendEmptyMessage(1);

    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        // 外部类Activity生命周期结束时，同时清空消息队列 和 结束Handler生命周期
        calThread.mHandler.removeCallbacksAndMessages(null);
    }
}